package top.system.dept.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Base64.*;

/**
 * @ClassName: SecurityUtil
 * @Author: Amosen
 * @Since: 2021/5/16
 */
public class SecurityUtil {

    public static String encrypt32ForMD5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            byte[] md5Bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encrypt16ForMD5(String str) {
        return encrypt32ForMD5(str).substring(8, 24);
    }

    public static String encryptForBase64(String str) {
        Encoder encoder = Base64.getEncoder();
        byte[] encrypt = encoder.encode(str.getBytes(StandardCharsets.UTF_8));
        return new String(encrypt);
    }

    public static String decodeForBase64(String str) {
        Decoder decoder = Base64.getDecoder();
        byte[] decode = decoder.decode(str);
        return new String(decode);
    }

}
